package com.xing.config.ds.rw;

import com.xing.config.ds.rw.common.DynamicDataSource;
import com.xing.enumeration.DBTypeEnum;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Bradish7Y on 2017/8/24.
 */
@Configuration
@ImportResource({"classpath:spring/rw/spring-transaction-rw.xml"})
public class RWDataSourceConfig {

    @Value("${spring.datasource.type}")
    private Class<? extends DataSource> dataSourceType;

    /**
     * 配置druid数据源，需配置，否则不生效
     */
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.write")
    public DataSource dataSource_write() {
        return DataSourceBuilder.create().type(dataSourceType).build();
    }

    /**
     * 配置druid数据源，需配置，否则不生效
     */
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.read")
    public DataSource dataSource_read() {
        return DataSourceBuilder.create().type(dataSourceType).build();
    }

    @Bean
    public DataSource dataSource_rw() {
        DynamicDataSource ds = new DynamicDataSource();

        Map<Object, Object> sourceMap = new HashMap<>();
        sourceMap.put(DBTypeEnum.READ.getValue(), dataSource_read());
        sourceMap.put(DBTypeEnum.WRITE.getValue(), dataSource_write());
        ds.setTargetDataSources(sourceMap);

        /**
         * 这里一定要这样写，写字符串会报错（jndi lookup失败）
         */
        ds.setDefaultTargetDataSource(dataSource_write());

        return ds;
    }

//    /**
//       * 单数据源，可以这样配置
//     * mybatis-plus分页插件<br>
//     * 文档：http://mp.baomidou.com<br>
//     */
//    @Bean
//    public PaginationInterceptor paginationInterceptor() {
//        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
//        paginationInterceptor.setLocalPage(true);// 开启 PageHelper 的支持
//        return paginationInterceptor;
//    }

    @Bean
    public DataSourceTransactionManager RWTransactionManager() throws Exception {
        return new DataSourceTransactionManager(dataSource_rw());
    }

}
